package com.shenzw.common.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author shenzw
 * @date 2024/3/12
 */
@Component
@Slf4j
@WebFilter(filterName="responseFilter",urlPatterns= {"/*"})
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ResponseFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 使用自定义的 ResponseCaptureWrapper 包装 HttpServletResponse
        ResponseCaptureWrapper responseWrapper = new ResponseCaptureWrapper((HttpServletResponse) response);

        // 调用 FilterChain 的 doFilter 方法将请求传递给下一个过滤器或目标资源
        chain.doFilter(request, responseWrapper);

        // 获取捕获的响应内容
        String capturedResponse = responseWrapper.getCapturedResponse();
        log.info("Captured Response: {}", capturedResponse);

        // 将修改后的响应内容写回客户端
//        response.getWriter().write(capturedResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }


    // 其他方法的实现与之前相同
}

class ResponseCaptureWrapper extends HttpServletResponseWrapper {

    private CharArrayWriter charArrayWriter = new CharArrayWriter();

    public ResponseCaptureWrapper(HttpServletResponse response) {
        super(response);
    }

    @Override
    public PrintWriter getWriter() {
        return new PrintWriter(charArrayWriter);
    }

    public String getCapturedResponse() {
        return charArrayWriter.toString();
    }
}
